﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;

namespace KPIS.GERP.GHRMS.APP.Classes
{
    public class ComboboxUtilites
    {
        private int ItemsPerRequest = 10;

        public ComboboxUtilites()
        {

        }

        public ComboboxUtilites(int itemPerRequest)
        {
            ItemsPerRequest = itemPerRequest;
        }

        public List<string> BindComboBoxWithTableVirtualLoadToCurrent(ref RadComboBox comboBox,
                                                                      object bindList,
                                                                      List<string> columnNames,
                                                                      string fieldKeyToCompare,
                                                                      string fieldText,
                                                                      int itemCount,
                                                                      string selectedValue = null)
        {
            comboBox.Items.Clear();

            List<string> itemAdded = new List<string>(); // for debug
            string dataType = bindList.GetType().Name;
            int i = 0;
            const int itemOffSet = 0;
            int endOffset = itemOffSet + ItemsPerRequest;

            if (dataType.StartsWith("List"))
            {
                foreach (object data in (IEnumerable)bindList)
                {
                    string keyOfEachData = Convert.ToString(data.GetType().GetProperty(fieldKeyToCompare).GetValue(data, null));
                    string textOfEachData = Convert.ToString(data.GetType().GetProperty(fieldText).GetValue(data, null));

                    // Add Default Item
                    comboBox.Items.Add(new RadComboBoxItem(textOfEachData, keyOfEachData));

                    Table targetTable = (from Control c in comboBox.Items[i].Controls
                                         where c.GetType().Name == "Table"
                                         select (Table)c).FirstOrDefault();

                    if (targetTable == null)
                        throw new Exception(String.Format("Can not find any table in Template of combobox '{0}'.",
                                                          comboBox.ID));

                    int j = 0;
                    foreach (string kv in columnNames)
                    {
                        string fieldTextText = Convert.ToString(data.GetType().GetProperty(kv).GetValue(data, null));
                        targetTable.Rows[0].Cells[j++].Text = fieldTextText;
                        itemAdded.Add(fieldTextText);
                    }

                    if (keyOfEachData == selectedValue)
                    {
                        comboBox.Items[i].Selected = true;
                        endOffset = Math.Min(endOffset, itemCount);
                        comboBox.LoadingMessage = GetStatusMessage(endOffset, itemCount);
                        break;
                    }
                    i++;
                }
                return itemAdded;
            }

            if (dataType.StartsWith("DataTable"))
            {
                foreach (DataRow data in ((DataTable)bindList).Rows)
                {
                    string keyOfEachData = Convert.ToString(data[fieldKeyToCompare]);
                    string textOfEachData = Convert.ToString(data[fieldText]);

                    // Add Default Item
                    comboBox.Items.Add(new RadComboBoxItem(textOfEachData, keyOfEachData));

                    Table targetTable = (from Control c in comboBox.Items[i].Controls
                                         where c.GetType().Name == "Table"
                                         select (Table)c).FirstOrDefault();
                    if (targetTable == null)
                    {
                        string errorMessage = String.Format("Can not find any table in Template of combobox '{0}'.",
                                                            comboBox.ID);
                        throw new Exception(errorMessage);
                    }

                    int j = 0;
                    foreach (string kv in columnNames)
                    {
                        targetTable.Rows[0].Cells[j++].Text = Convert.ToString(data[kv]);

                        itemAdded.Add(Convert.ToString(data[kv]));
                    }

                    if (keyOfEachData == selectedValue)
                    {
                        comboBox.Items[i].Selected = true;
                        {
                            endOffset = Math.Min(endOffset, itemCount);
                            comboBox.LoadingMessage = GetStatusMessage(endOffset, itemCount);
                        }
                        break;
                    }

                    i++;
                }
                return itemAdded;
            }
            return null;
        }

        public void BindComboBoxWithTableItemRequest(ref RadComboBox comboBox,
                                                     object bindList,
                                                     List<string> columnNames,
                                                     string fieldKeyToCompare,
                                                     string fieldText,
                                                     ref RadComboBoxItemsRequestedEventArgs e,
                                                     int itemCount)
        {
            string selectedValue = comboBox.SelectedValue;

            var alreadyInComboBox = new List<string>();
            foreach (RadComboBoxItem item in comboBox.Items)
            {
                alreadyInComboBox.Add(item.Value);
            }

            comboBox.Items.Clear();

            var dataType = bindList.GetType().Name;
            int i = 0, itemOffSet = e.NumberOfItems;
            int endOffset = itemOffSet + ItemsPerRequest;


            if (dataType.StartsWith("List"))
            {
                foreach (object data in (IEnumerable)bindList)
                {
                    if (endOffset == i)
                    {
                        endOffset = Math.Min(endOffset, itemCount);
                        e.Message = GetStatusMessage(endOffset, itemCount);
                        return;
                    }

                    string keyOfEachData =
                        Convert.ToString(data.GetType().GetProperty(fieldKeyToCompare).GetValue(data, null));
                    string textOfEachData = Convert.ToString(data.GetType().GetProperty(fieldText).GetValue(data, null));

                    if (selectedValue == keyOfEachData)
                        continue;

                    if (i >= itemOffSet && !alreadyInComboBox.Contains(keyOfEachData))
                    {
                        // Add Default Item
                        comboBox.Items.Add(new RadComboBoxItem(textOfEachData, keyOfEachData));

                        Table targetTable = (from Control c in comboBox.Items[i].Controls
                                             where c.GetType().Name == "Table"
                                             select (Table)c).FirstOrDefault();
                        if (targetTable == null)
                        {
                            string errorMessage = String.Format(
                                "Can not find any table in Template of combobox '{0}'.", comboBox.ID);
                            throw new Exception(errorMessage);
                        }

                        int j = 0;
                        foreach (string kv in columnNames)
                        {
                            string fieldTextText = Convert.ToString(data.GetType().GetProperty(kv).GetValue(data, null));
                            targetTable.Rows[0].Cells[j++].Text = fieldTextText;
                        }

                        if (keyOfEachData == selectedValue)
                        {
                            comboBox.Items[i].Selected = true;
                        }
                    }
                    i++;
                }
            }


            if (dataType.Equals("DataTable") || dataType.Equals("DataSet"))
            {
                bindList = dataType.StartsWith("DataSet") ? ((DataSet)bindList).Tables[0] : bindList;

                foreach (DataRow data in ((DataTable)bindList).Rows)
                {
                    if (endOffset == i)
                    {
                        endOffset = Math.Min(endOffset, itemCount);
                        e.Message = GetStatusMessage(endOffset, itemCount);
                        return;
                    }

                    string keyOfEachData = Convert.ToString(data[fieldKeyToCompare]);
                    string textOfEachData = Convert.ToString(data[fieldText]);

                    if (i >= itemOffSet && !alreadyInComboBox.Contains(keyOfEachData))
                    {
                        // Add Default Item
                        comboBox.Items.Add(new RadComboBoxItem(textOfEachData, keyOfEachData));

                        Table targetTable = (from Control c in comboBox.Items[comboBox.Items.Count - 1].Controls
                                             where c.GetType().Name == "Table"
                                             select (Table)c).FirstOrDefault();

                        if (targetTable == null)
                        {
                            string errorMessage = String.Format(
                                "Can not find any table in Template of combobox '{0}'.", comboBox.ID);
                            throw new Exception(errorMessage);
                        }

                        int j = 0;
                        foreach (string kv in columnNames)
                        {
                            targetTable.Rows[0].Cells[j++].Text = Convert.ToString(data[kv]);
                        }

                        if (keyOfEachData == selectedValue)
                        {
                            comboBox.Items[comboBox.Items.Count - 1].Selected = true;
                        }
                    }
                    i++;
                }
            }
        }

        public string GetStatusMessage(int offset, int total)
        {
            return total <= 0 ? "ไม่มีข้อมูล" : String.Format("ที่ <b>1</b>-<b>{0}</b> จาก <b>{1}</b> รายการ", offset, total);
        }

    }
}